<template>
  <div>
    <van-nav-bar title="商铺信息" left-text="返回" right-text="按钮" @click-left="onClickLeft" @click-right="onClickRight">
      <van-icon name="more" slot="left" size="1.4em" />
      <van-icon name="edit" slot="right" size="1.4em" />
    </van-nav-bar>
    <van-cell-group>
      <!-- <van-cell title="商铺信息">
      </van-cell> -->
      <van-field left-icon="shop" label="商户名称" :readonly="!editable" v-model="shopInfo.name" placeholder="请输入用户名" center clearable />
      <van-field left-icon="username" label="负责人" :readonly="!editable" v-model="shopInfo.managerName" placeholder="请输入用户名" center clearable />
      <van-field left-icon="mobile" label="手机" :readonly="!editable" v-model="shopInfo.managerMobile" placeholder="请输入用户名" center clearable />
      <van-field left-icon="address" label="地址" :readonly="!editable" v-model="shopInfo.addr" placeholder="请输入用户名" center clearable />
      <van-cell icon="smoke-sensor2" title="设备" :value="deviceCount" is-link :arrow-direction="devicesCollapsed?'right':'down'" @click="toggleCollapse" />
    </van-cell-group>
    <div>
      <van-swipe-cell :right-width="delWidth" :on-close="onClose" v-for="(item, index) in items" :key="index" v-show="!devicesCollapsed">
        <van-cell-group :border="true">
          <van-cell :value="item.imei" icon="smoke-sensor2">
            <template slot="title">
              <span class="van-cell-text">{{item.devName}}</span>
              <van-tag type="danger">{{item.devModel}}</van-tag>
            </template>
          </van-cell>
        </van-cell-group>
        <van-button slot="right" class="van-swipe-cell__right" :style="{'width':delWidth+'px'}" tag="div" @click="unBindDevice(item.imei)">
          解绑
        </van-button>
      </van-swipe-cell>
    </div>
    <div class="operaiton-button" v-show="editable">
      <van-button size="large" type="danger" :loading="isLoading" @click="submiteSave">确认修改</van-button>
    </div>
    <transition name="fade">
      <div class="function-panel" v-show="functionPanelShow">
        <div class="triangle-up"></div>
        <div class="van-cell van-cell--center  function-item" @click="sanQRCode"><i class="van-icon van-icon-qr van-cell__left-icon"></i>
          <div class="van-cell__title"><span>二维码绑定设备</span>

          </div>
        </div>
        <div class="van-cell van-cell--center  function-item" @click="addDevice"><i class="van-icon van-icon-add van-cell__left-icon"></i>
          <div class="van-cell__title"><span>手动添加设备</span>

          </div>
        </div>
      </div>
    </transition>

    <van-popup v-model="addDeviceShow" position="top" :overlay="true">
      <div style="padding:10px 30px 20px">
        <div style="text-align:center;font-size:18px;padding:10px;">绑定设备</div>
        <van-cell-group>
          <van-field v-model="deviceForm.imei" required clearable left-icon="imei" label="IMEI" placeholder="请输入IMEI号" :error-message="errorMsg.imei" />
          <van-field v-model="deviceForm.installAddr" required clearable left-icon="address" label="安装地址" placeholder="请输安装地址" :error-message="errorMsg.installAddr" />
        </van-cell-group>
        <van-button size="large" type="danger" :loading="isLoading" @click="submitBindDevice">提交绑定</van-button>

      </div>

    </van-popup>

  </div>
</template>

<script>
import wx from "weixin-js-sdk";
import {
  getShopInfo,
  saveShop,
  getDevices,
  bindDevice,
  unBindDevice
} from "./../../api/building";
import validator from "@/libs/validator";
export default {
  data() {
    return {
      shopId: 0,
      shopInfo: {
        id: 0,
        addr: "光谷金融港",
        dutyLetter: null,
        managerMobile: "18627771160",
        managerName: "刘恒",
        name: "飞发走丝",
        alarmNotifier: ""
      },
      items: [],
      isLoading: false,
      editable: false,
      functionPanelShow: false,
      addDeviceShow: false,
      devicesCollapsed: true,
      deviceCount: 0,
      items: [],
      deviceForm: {
        imei: "",
        installAddr: ""
      },
      errorMsg: {
        imei: "",
        installAddr: ""
      },
      rules: {
        imei: [{ required: true, message: "请输入imei号" }],
        installAddr: [{ required: true, message: "请输入安装地址" }]
      }
    };
  },
  computed: {
    delWidth() {
      return window.innerWidth * 0.2;
    }
  },
  watch: {},
  created() {
    this.validator = validator(this.rules, this.deviceForm);
  },
  mounted() {
    this.shopId = this.$route.query;
    this.getShopInfo();
    this.getDevices();
  },
  activated() {},
  deactivated() {},
  methods: {
    async getShopInfo() {
      let res = await getShopInfo({ id: this.shopId });
      if (res.code === 0) {
        this.shopInfo = res.data;
      } else {
        this.$toast.fail(res.msg);
      }
    },
    async submiteSave() {
      this.isLoading = true;
      let res = await saveShop(this.shopInfo);
      if (res.code === 0) {
        this.editable = false;
        this.$toast.success("修改成功");
      } else {
        this.$toast.fail(res.msg);
      }
      this.isLoading = false;
    },
    onClickLeft() {
      this.functionPanelShow = !this.functionPanelShow;
    },
    onClickRight() {
      this.editable = true;
    },
    toggleCollapse() {
      this.devicesCollapsed = !this.devicesCollapsed;
    },
    async getDevices() {
      let res = await getDevices({ id: this.shopId });
      if (res.code === 0) {
        this.deviceCount = res.data.total;
        this.items = res.data.data;
      } else {
        this.$toast.fail(res.msg);
      }
    },
    onClose(clickPosition, instance) {
      const vm = this;
      const IMEI = instance.$children[0].$children[0].value;
      switch (clickPosition) {
        case "left":
        case "cell":
        case "outside":
          instance.close();
          break;
        case "right":
          this.$dialog
            .confirm({
              message: "确定解绑？"
            })
            .then(() => {
              vm.submitUnBindDevice(IMEI);
              instance.close();
            })
            .catch(() => {
              // on cancel
            });
          break;
      }
    },
    sanQRCode() {
      this.functionPanelShow = false;
      this.deviceForm.installAddr = "";
      this.resetField();
      const vm = this;
      wx.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        scanType: ["qrCode"], // 可以指定扫二维码还是一维码，默认二者都有
        success: function(res) {
          try {
            let result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
            let IMEI = result.split("&")[0].split("=")[1];
            if (IMEI) {
              vm.deviceForm.imei = IMEI;
              vm.addDeviceShow = true;
            } else {
              vm.$toast("请扫描烟感设备二维码");
            }
          } catch (error) {
            vm.$toast("请扫描烟感设备二维码");
          }
        }
      });
    },
    /**
     * 验证方法
     * @param callback
     * @param data
     */
    validate(callback, data) {
      this.validator.validate((errors, fields) => {
        this.resetField();
        if (errors) {
          
          fields.forEach(item => {
            this.errorMsg[item.field] = item.message;
          });
        }
        callback && callback(errors, fields);
      }, data);
    },
    /**
     * 清除验证提示
     * @param attrs
     */
    resetField(attrs) {
      attrs = !attrs
        ? Object.keys(this.errorMsg)
        : Array.isArray(attrs)
          ? attrs
          : [attrs];
      attrs.forEach(attr => {
        this.errorMsg[attr] = "";
      });
    },
    addDevice() {
      this.functionPanelShow = false;
      this.deviceForm.imei = "";
      this.deviceForm.installAddr = "";
      this.resetField();
      this.addDeviceShow = true;
    },
    async submitBindDevice() {
      this.isLoading = true;
      this.validate(async (errors, fields) => {
        if (!errors) {
          let res = await bindDevice({
            imei: this.deviceForm.imei,
            installAddr: this.deviceForm.installAddr,
            bd_id: this.shopId
          });
          if (res.code === 0) {
            this.$toast.success("设备绑定成功！");
            this.getDevices();
          } else {
            this.$toast.fail(res.msg);
          }
        }
      });

      this.isLoading = false;
    },
    async submitUnBindDevice(IMEI) {
      let res = await unBindDevice({ imei: IMEI });
      if (res.code === 0) {
        this.$toast.success("设备解绑成功！");
        this.getDevices();
      } else {
        this.$toast.fail(res.msg);
      }
    }
  }
};
</script>


<style lang="scss" scoped>
@import "./../../../../assets/scss/mixin";
.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.fade-enter-active,
.fade-leave-active {
  transition: all 0.5s;
}

.sub-wrapper {
  display: flex;
  margin-top: 10px;
  padding: 20px;
  background-color: #fff;
  .sub-item {
    flex: 1;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 40vw;
    border: 1px solid #eee;
  }
}
.van-swipe-cell {
  &__left,
  &__right {
    color: #ffffff;
    font-size: 14px;
    height: 100%;
    display: inline-block;
    text-align: center;
    display: flex;
    align-items: center; /*垂直居中*/
    justify-content: center; /*水平居中*/
    background-color: #f44;
  }
}
.function-panel {
  width: 160px;
  position: absolute;
  top: 45px;
  z-index: 9999;
  .triangle-up:before {
    content: "";
    position: absolute;
    top: -20px;
    left: 14px;
    width: 0;
    height: 0;
    border-top: 10px solid transparent;
    border-bottom: 10px solid #666;
    border-right: 10px solid transparent;
    border-left: 10px solid transparent;
  }
  .function-item {
    color: #fff;
    display: flex;
    align-items: center;
    background-color: #666;
  }
  &:activated {
    background-color: #e8e8e8;
  }
}
</style>
